package db

import (
	"sync"
)

// ----------------------------------------
//  GORM 客户端管理器
// ----------------------------------------
type GORMClientManager struct {
	rw      *sync.RWMutex
	clients map[string]*GORMClient
}

// 创建 GORM 客户端管理器实例
func CreateGORMClientManager() *GORMClientManager {
	return &GORMClientManager{rw: &sync.RWMutex{}, clients: make(map[string]*GORMClient)}
}

// 获取给定名称的 GORM 客户端实例（如果客户端不存在则返回 nil）
func (manager *GORMClientManager) Get(name string) *GORMClient {
	manager.rw.RLock()
	defer manager.rw.RUnlock()
	if client, exists := manager.clients[name]; exists {
		return client
	} else {
		return nil
	}
}

// 添加或更新 GORM 客户端实例
func (manager *GORMClientManager) Set(name string, client *GORMClient) {
	manager.rw.Lock()
	manager.clients[name] = client
	manager.rw.Unlock()
}

// 清空 GORM 客户端实例
func (manager *GORMClientManager) Clear() {
	manager.rw.Lock()
	manager.rw.Unlock()

	for k := range manager.clients {
		delete(manager.clients, k)
	}
}
